#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;

const int N = 2e5 + 10;
int n, m;

// 稠密图用邻接矩阵，稀疏图用邻接表
int e[N], g[N], ne[N], w[N], idx;
// st数组判断是否已经确定最短路
bool st[N];
// dist数组存放距离，刚开始应该初始化为无穷大
int dist[N];
// 用一个优先级队列来优化查找当前最短路的过程
// 并且优先级队列还要能够存储结点位置
// 优先级队列默认是大根堆，应该使用小根堆
priority_queue<PII, vector<PII>, greater<PII>> q;

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = g[a], g[a] = idx++;
}

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    q.push({0, 1});
    dist[1] = 0;
    while (!q.empty())
    {
        auto p = q.top();
        q.pop();
        int pos = p.second, distance = p.first;
        if (pos == n)
            return dist[n];
        if (st[pos])
            continue;
        st[pos] = true;
        for (int i = g[pos]; ~i; i = ne[i])
        {
            int j = e[i];
            // 更新最小距离，并且入堆
            if (!st[j] && distance + w[i] < dist[j])
            {
                dist[j] = distance + w[i];
                q.push({dist[j], j});
            }
        }
    }
    return -1;
}

int main()
{
    memset(g, -1, sizeof g);
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for (int i = 0; i < m; ++i)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    int t = dijkstra();
    cout << t << endl;
    return 0;
}
